package com.glodon.paas.qto.dao.impl;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.glodon.paas.job.model.TaskStatus;
import com.glodon.paas.qto.dao.TaskRepositoryCustom;
import com.glodon.paas.qto.model.TaskProgress;

public class TaskRepositoryJpaImpl implements TaskRepositoryCustom {
    private final String MODIFY_VIRTUALTASK = "UPDATE Task t SET t.responseTime=:responseTime WHERE t.responseTime is null AND t.id=:id ";
    private final String CHILDTASK_COMPLETECOUNT = "SELECT count(*) FROM Task t WHERE t.status=:status AND t.parentId=:parentId ";
    private final String MODIFY_TASK_PROGRESS = "UPDATE Task t SET t.responseTime=:responseTime, t.progress=:progress, " + 
            "t.status=:status, t.message=:message ";
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public boolean modifyVirtualTask(String taskId) {
        Query query = entityManager.createQuery(MODIFY_VIRTUALTASK);
        query.setParameter("responseTime", new Date());
        query.setParameter("id", taskId);
        int update = query.executeUpdate();
        return update > 0;
    }

    @Override
    public long getChildTaskCompleteCount(String parentId) {
        Query query = entityManager.createQuery(CHILDTASK_COMPLETECOUNT);
        query.setParameter("status", TaskStatus.success);
        query.setParameter("parentId", parentId);
        long count = (Long)query.getSingleResult();
        return count;
    }

    @Override
    public boolean modifyTaskProgress(String taskId, TaskProgress progress) {
        String jpql = null;
        TaskStatus status = progress.getStatus();
        if (status == null) {//未知状态
            return false;
        }
        if (TaskStatus.success.equals(status) || TaskStatus.failure.equals(status) || TaskStatus.canceled.equals(status)) {
            jpql = MODIFY_TASK_PROGRESS + "WHERE t.jobServerTaskId = :taskId";
        } else {
            jpql = MODIFY_TASK_PROGRESS + "WHERE t.progress < :progress AND t.jobServerTaskId = :taskId";
        }
        Query query = entityManager.createQuery(jpql);
        query.setParameter("responseTime", new Date());
        query.setParameter("progress", progress.getProgress());
        query.setParameter("status", status);
        query.setParameter("message", progress.getMessage());
        if (TaskStatus.success.equals(status) || TaskStatus.failure.equals(status) || TaskStatus.canceled.equals(status)) {
            query.setParameter("taskId", taskId);
        } else {
            query.setParameter("progress", progress.getProgress());
            query.setParameter("taskId", taskId);
        }
        int update = query.executeUpdate();
        return update > 0;
    }
}
